import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/RegisterView.vue')
  },
  {
    path: '/products',
    name: 'products',
    component: () => import('../views/ProductListView.vue')
  },
  {
    path: '/product/:id',
    name: 'productDetail',
    component: () => import('../views/ProductDetailView.vue')
  },
  {
    path: '/cart',
    name: 'cart',
    component: () => import('../views/CartView.vue')
  },
  {
    path: '/checkout',
    name: 'checkout',
    component: () => import('../views/CheckoutView.vue')
  },
  {
    path: '/orders',
    name: 'orders',
    component: () => import('../views/OrderListView.vue')
  },
  {
    path: '/order/:id',
    name: 'orderDetail',
    component: () => import('../views/OrderDetailView.vue')
  },
  {
    path: '/profile',
    name: 'profile',
    component: () => import('../views/UserProfileView.vue')
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/AboutView.vue')
  },
  {
    path: '/test-message',
    name: 'testMessage',
    component: () => import('../views/TestMessageView.vue')
  },
  {
    path: '/admin',
    name: 'admin',
    redirect: '/admin/dashboard',
    component: () => import('../views/admin/AdminLayout.vue'),
    children: [
      {
        path: 'dashboard',
        name: 'adminDashboard',
        component: () => import('../views/admin/DashboardView.vue')
      },
      {
        path: 'users',
        name: 'adminUsers',
        component: () => import('../views/admin/UserManagement.vue')
      },
      {
        path: 'categories',
        name: 'adminCategories',
        component: () => import('../views/admin/CategoryManagement.vue')
      },
      {
        path: 'products',
        name: 'adminProducts',
        component: () => import('../views/admin/ProductManagement.vue')
      },
      {
        path: 'orders',
        name: 'adminOrders',
        component: () => import('../views/admin/OrderManagement.vue')
      }
    ]
  },
  {
    path: '/admin/login',
    name: 'adminLogin',
    component: () => import('../views/admin/AdminLoginView.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
  // 配置页面跳转时的滚动行为
  scrollBehavior(to, from, savedPosition) {
    // 如果有保存的位置（比如浏览器后退），则恢复到该位置
    if (savedPosition) {
      return savedPosition
    }
    // 如果有锚点，则滚动到锚点位置
    if (to.hash) {
      return {
        el: to.hash,
        behavior: 'smooth'
      }
    }
    // 否则滚动到页面顶部
    return { top: 0, behavior: 'smooth' }
  }
})

export default router
